package com.crl.module.loaders
{
	import com.crl.module.loaders.workers.Worker;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	
	
	/**
	 * 
	 * @author crl
	 * 
	 */	
	public class QueueWorker extends Worker implements IQueueWorker
	{
		private var works:Vector.<Worker>
		private var pointer:int;
		
		private var total:int;
		private var loaded:int;
		
		public function QueueWorker(works:Vector.<Worker>)
		{
			this.works=works;
			if(works is IQueueWorker){
				//todo if item is iqueue;
			}
			this.total=works.length;
		}
		
		public function get itemTotal():int{
			return this.total;
		} 
		public function get itemLoaded():int{
			return this.loaded;
		}
		
		
		public function start():void{
			_data=[];
			
			pointer=-1;
			loadNext();
		}
		
		protected function loadNext():void{
			if(pointer<works.length-1){
				pointer++;
				
				loader=works[pointer];
				var w:Worker=loader;
				w.addEventListener(Event.COMPLETE,completeHandler);
				w.addEventListener(ErrorEvent.ERROR,errorHandler);
				w.start();
				
			}else{
				this.onComplete(new Event(Event.COMPLETE));
			}
		}
		
		private function errorHandler(event:Event):void{
			this.loadNext();
		}
		
		private function completeHandler(event:Event):void{
			var w:Worker=event.target as Worker;
			w.removeEventListener(Event.COMPLETE,completeHandler);
			w.removeEventListener(ErrorEvent.ERROR,errorHandler);
			
			_data.push(w.data);
			
			loaded++;
			//todo dis itemevent;
			//this.dispatchEvent(Event.
			
			this.loadNext();
		}
		
	}
}